package com.aaa.service.impl;

import cn.hutool.json.JSONUtil;
import com.aaa.dao.SysUserDao;
import com.aaa.entity.SysUser;
import com.aaa.exceptions.CustomException;
import com.aaa.params.LoginParam;
import com.aaa.service.SysUserService;
import com.aaa.utils.FieldBasicVerifyUtil;
import com.aaa.utils.JwtUtil;
import com.aaa.utils.RedisUtil;
import com.aaa.vo.LoginVO;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 用户表(SysUser)表服务实现类
 *
 * @author makejava
 * @since 2025-05-08 18:10:51
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public LoginVO backendLogin(LoginParam loginParam) {
        //1、校验是否为空
        FieldBasicVerifyUtil.verifyFieldIsNotEmpty(loginParam);
        //2、校验是否存在
        int userVerifyCount = this.count(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getUsername, loginParam.getUsername())
                .eq(SysUser::getPassword, loginParam.getPassword())
                .eq(SysUser::getDelFlag, 0));
        if (userVerifyCount == 0) {
            throw new CustomException("用户名或密码错误");
        }
        //3、获取用户信息
        SysUser sysUser = this.getOne(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getUsername, loginParam.getUsername()));
        //4、返回用户信息
        LoginVO loginVO = new LoginVO();
        String token = JwtUtil.generateToken(sysUser.getUsername());
        redisUtil.setEx(token, JSONUtil.toJsonStr(sysUser), 60 * 60 * 12,  TimeUnit.SECONDS);
        loginVO.setToken(token);
        loginVO.setUsername(sysUser.getUsername());
        return loginVO;
    }
}

